<?php


namespace app\admin\controller;


use think\Db;
use think\Exception;
use \think\facade\Log;
use think\Request;
use think\Validate;

class RoleController extends CommonController
{
    private static $ROLE_TABLE="role";
    private static $PERMISSION_TABLE="permission";
    private static $PERMISSION_ROLE_TABLE="permission_role";

    public function GetRoleOption()
    {
        $res=Db::table(self::$ROLE_TABLE)
            ->where('delete_flag','=',0)
            ->where('status','=',0)
            ->select();
        return returnSuccess($res,'success');
    }
    public function addRole(Request $request)
    {
        $data=$request->param('data');
        $rule = [
            'name'  => 'require|max:10',
            'info'   => 'require|max:20',
        ];
        $message  = [
            'name.require' => '角色名称必填',
            'name.max' => '角色名称最多10个字符',
            'info.require'=> '角色简介必填',
            'info.max' => '角色简介最多20个字符',
        ];
        $validate = Validate::make($rule,$message);
        $result = $validate->check($data);
        if(!$result) {
           return returnFail($validate->getError());
        }
        if (!isset($data['pid'])||empty($data['pid'])){
            $data['pid']=0;
        }
        $is_set=Db::table(self::$ROLE_TABLE)
            ->where('delete_flag','=',0)
            ->where('name','=',$data['name'])
            ->find();
        if ($is_set){
            return returnFail('角色名称重复');
        }

        $tree=$request->param('tree');
        //处理选择权限
        $trees=[];
        foreach ($tree as $k=>$v){
            $trees[]=$v['id'];
            $trees[]=$v['pid'];
            $pid_see= DB::table(self::$PERMISSION_TABLE)
                ->where('id','=',$v['pid'])
                ->where('delete_flag','=',0)
                ->where('status','=',0)
                ->value('pid');
            if ($pid_see!=0){
                $trees[]=$pid_see;
            }
        }
        //去重
        $trees=array_unique($trees);
        if (empty($trees)){
            return returnFail('请选择权限');
        }

        try {
            Db::startTrans();
            $insert_data=[
                'name'=>$data['name'],
                'info'=>$data['info'],
                'pid'=>$data['pid'],
                'created_by'=>0,
                'created_time'=>date("Y-m-d H:i:s",time())
            ];
           $role_id = Db::table(self::$ROLE_TABLE)->insertGetId($insert_data);
            foreach ($trees as $k=>$v){
                if ($v!=0){
                    Db::table(self::$PERMISSION_ROLE_TABLE)
                        ->insert(['role_id'=>$role_id,'permission_id'=>$v,'created_by'=>$this->getUserId($request->header('token')),'created_time'=>date("Y-m-d H:i:s",time())]);
                  }
            }
            Db::commit();
            return returnSuccess([],'添加成功');
        }catch (Exception $e){
            Db::rollback();
            return returnFail($e->getMessage());
        }

    }

    public function GetRoleList(Request $request)
    {
        $page=$request->get('page')?:self::$Page;
        $limit=$request->get('limit')?:self::$Limit;
        $res= DB::table(self::$ROLE_TABLE)
            ->alias('a')
            ->where(function ($query)use ($request){
                $query->where('a.delete_flag','=',0);
                if ($request->get('val')!=null||!empty($request->get('val'))){
                    $query->where('a.name','like','%'.$request->get('val').'%');
                }
            })
            ->field('a.id,a.name,a.info,a.status,a.pid')
            ->fieldRaw('(select b.name from role as b where b.delete_flag = 0 and b.status= 0 and b.id = a.pid) as p_name')
            ->limit($limit)
            ->page($page)
            ->select();
        $total= Db::table(self::$ROLE_TABLE)->where('delete_flag','=',0)->count();
        $fenye=['limit'=>$limit,'page'=>$page,'total'=>$total];
        $data=['res'=>$res,'fenye'=>$fenye];
        return returnSuccess($data,'success');
    }

    public function GetCheckedTree(Request $request)
    {
        $res= DB::table('role')
            ->alias('a')
            ->join('permission_role b','a.id = b.role_id')
            ->join('permission c','c.id = b.permission_id')
            ->where('a.delete_flag','=','0')
            ->where('a.status','=','0')
            ->where('b.delete_flag','=','0')
            ->where('b.status','=','0')
            ->where('c.delete_flag','=','0')
            ->where('c.status','=','0')
            ->where('a.id','=',$request->get('role_id'))
            ->field('c.id')
            ->select();
        return returnSuccess($res,'success');
    }

    public function CheckRoleStatus(Request $request)
    {
        if (!$request->get('id')){
            return returnFail('缺少参数');
        }
        $status=$request->get('status')==1?1:0;
        try {
            Db::table(self::$ROLE_TABLE)->where('id','=',$request->get('id'))->update(['status'=>$status,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
           return returnSuccess([],'更新成功');
        }catch (Exception $e){
            return returnFail($e->getMessage());
        }
    }

    public function updateRole(Request $request)
    {
        $data=$request->param('data');
        $rule = [
            'name'  => 'require|max:10',
            'info'   => 'require|max:20',
            'id'=>'require'
        ];
        $message  = [
            'name.require' => '角色名称必填',
            'name.max' => '角色名称最多10个字符',
            'info.require'=> '角色简介必填',
            'info.max' => '角色简介最多20个字符',
            'id.require'=>'参数错误'
        ];
        $validate = Validate::make($rule,$message);
        $result = $validate->check($data);
        if(!$result) {
            return returnFail($validate->getError());
        }
        if (!isset($data['pid'])||empty($data['pid'])){
            $data['pid']=0;
        }
        $is_set=Db::table(self::$ROLE_TABLE)
            ->where('delete_flag','=',0)
            ->where('name','=',$data['name'])
            ->where('id','<>',$data['id'])
            ->find();
        if ($is_set){
            return returnFail('角色名称重复');
        }

        $tree=$request->param('tree');
        //处理选择权限
        $trees=[];
        foreach ($tree as $k=>$v){
            $trees[]=$v['id'];
            $trees[]=$v['pid'];
            $pid_see= DB::table(self::$PERMISSION_TABLE)
                ->where('id','=',$v['pid'])
                ->where('delete_flag','=',0)
                ->where('status','=',0)
                ->value('pid');
            if ($pid_see!=0){
                $trees[]=$pid_see;
            }
        }
        //去重
        $trees=array_unique($trees);
        if (empty($trees)){
            return returnFail('请选择权限');
        }
        try {
            Db::startTrans();
            $update_data=[
                'name'=>$data['name'],
                'info'=>$data['info'],
                'pid'=>$data['pid'],
                'update_by'=>$this->getUserId($request->header('token')),
                'update_time'=>date("Y-m-d H:i:s",time())
            ];
            //更新角色表
            Db::table(self::$ROLE_TABLE)->where('id','=',$data['id'])->update($update_data);
            //处理角色权限关系
            Db::table(self::$PERMISSION_ROLE_TABLE)->where('role_id','=',$data['id'])->update(['delete_flag'=>1,'status'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date("Y-m-d H:i:s",time())]);
            foreach ($trees as $k=>$v){
                if ($v!=0){
                    //查询数据库是否有记录 有记录直接更新
                    $is_has=Db::table(self::$PERMISSION_ROLE_TABLE)
                        ->where('permission_id','=',$v)
                        ->where('role_id','=',$data['id'])
                        ->value('id');
                    if ($is_has){
                        Db::table(self::$PERMISSION_ROLE_TABLE)
                            ->where('id','=',$is_has)
                            ->update(['delete_flag'=>0,'status'=>0,'update_by'=>0,'update_time'=>date("Y-m-d H:i:s",time())]);
                    }else{
                        Db::table(self::$PERMISSION_ROLE_TABLE)->insert(['role_id'=>$data['id'],'permission_id'=>$v,'created_by'=>$this->getUserId($request->header('token')),'created_time'=>date("Y-m-d H:i:s",time())]);
                    }
                }
            }
            Db::commit();
            return returnSuccess([],'更新成功');
        }catch (Exception $e){
            Db::rollback();
            return returnFail($e->getMessage());
        }

    }

    public function DelRole(Request $request)
    {
        if (!$request->param('role_id')){
            return returnFail('参数不完整');
        }
        //先查询是否有账户是在使用此角色
        $is_exists= DB::table(self::$ROLE_TABLE)
            ->alias('a')
            ->join('user_role b','a.id = b.role_id')
            ->join('user c','c.id = b.user_id')
            ->where('a.delete_flag','=',0)
            ->where('b.delete_flag','=',0)
            ->where('c.delete_flag','=',0)
            ->where('a.id','=',$request->param('role_id'))
            ->find();
        if ($is_exists){
            return returnFail('请先删除正在使用此角色的账号');
        }
        try {
            DB::startTrans();
            DB::table(self::$ROLE_TABLE)->where('id','=',$request->param('role_id'))->update(['delete_flag'=>1,'status'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            DB::table(self::$ROLE_TABLE)->where('pid','=',$request->param('role_id'))->update(['delete_flag'=>1,'status'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            //处理角色权限关系表
            DB::table(self::$PERMISSION_ROLE_TABLE)->where('role_id','=',$request->param('role_id'))->update(['delete_flag'=>1,'status'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            $role_child_list=DB::table(self::$ROLE_TABLE)->where('pid','=',$request->param('role_id'))->field('id')->select();
            foreach ($role_child_list as $k=>$v){
                DB::table(self::$PERMISSION_ROLE_TABLE)->where('role_id','=',$v['id'])->update(['delete_flag'=>1,'update_by'=>$this->getUserId($request->header('token')),'update_time'=>date('Y-m-d H:i:s',time())]);
            }
            DB::commit();
            return returnSuccess([],'删除成功');
        }catch (\Exception $e){
            DB::rollBack();
            return returnFail($e->getMessage());
        }
    }

    public function GetRoleAll()
    {
        $res=DB::table(self::$ROLE_TABLE)
            ->where('delete_flag','=',0)
            ->where('status','=',0)
            ->field('id,name')
            ->select();
        return returnSuccess($res,'success');
    }





}